package com.wswy.wzcx.ui.car.remind

import android.app.DatePickerDialog
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.other.DialogFactory
import com.wswy.wzcx.utils.append0
import kotlinx.android.synthetic.main.fragment_add_insurance.*
import java.util.*

/**
 * 添加修改保修信息
 */
class InsuranceAddFragment : CBaseFragment() {

    private lateinit var remindViewModel: RemindViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_add_insurance,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        remindViewModel=provideViewModelFromActivity(RemindViewModel::class.java)
        remindViewModel.loadCompany()
        tv_car_no.text = remindViewModel.userCarInfo.carNo
        v_choose_date.setUI("上次投保时间","请选择")
        v_choose_company.setUI("上次投保公司","请选择")

        remindViewModel.userCarInfo.carExtendInfo?.insuranceInfo?.run {
            v_choose_date.setSelectedValue(date)
            v_choose_company.setSelectedValue(company)
            try {
                date?.split("-")?.let {
                    remindViewModel.addInsuranceSaveChoose(it[0].toInt(),it[1].toInt()-1,it[2].toInt())
                }
            }catch (e:Throwable){
                e.printStackTrace()
            }

        }


        v_choose_date.onClick {
            showChooseDate()
        }

        v_choose_company.onClick { _ ->
            showCompany {
                v_choose_company.setSelectedValue(it)
            }
        }

        btn_save_insurance.onClick {
            //保存
            save()
        }

    }

    private fun showChooseDate() {
        val calendar = Calendar.getInstance()

        DialogFactory.createDatePickerDialog(context, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->

            remindViewModel.addInsuranceSaveChoose(year, month, dayOfMonth)

            v_choose_date.setSelectedValue("$year-${(month+1).append0()}-${dayOfMonth.append0()}")

        }, remindViewModel.addInsuranceStatus.year,
                remindViewModel.addInsuranceStatus.month,
                remindViewModel.addInsuranceStatus.dayOfMonth).run {
            val datePicker = datePicker
            datePicker.maxDate = calendar.timeInMillis
            show()
        }

    }


    private fun showCompany(block:((String?)->Unit)){

        val list = remindViewModel.getCompanyList() ?: return

        AlertDialog.Builder(context!!).apply {

            setTitle("选择保险公司")
            setSingleChoiceItems(list,remindViewModel.addInsuranceStatus.company){ _, which ->
                remindViewModel.addInsuranceSaveChoose(company = which)
            }

            setPositiveButton(R.string.ok) { dialog, _ ->
                if (remindViewModel.addInsuranceStatus.company >=0){
                    block.invoke(list[remindViewModel.addInsuranceStatus.company])
                }
                dialog.dismiss()
            }

            setNegativeButton(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }

        }.run {
            show()
        }
    }


    private fun save(){
        val date = v_choose_date.getSelectedValue()
        val company = v_choose_company.getSelectedValue()
        if (TextUtils.isEmpty(date)){
            ToastUtils.showText("请选择上次投保时间")
            return
        }

        if (TextUtils.isEmpty(company)){
            ToastUtils.showText("请选择投保公司")
            return
        }

        StatTools.sendClick(context, StatisticsId.addinsurance_save)

        val dialog = LoadingDialog(context,"")

        remindViewModel.addInsurance(date?.toString(),company?.toString())

        remindViewModel.getAddInsuranceLiveData().observe(this,android.arch.lifecycle.Observer {

            it?.run {

                if(inLoading()){
                    btn_save_insurance.isClickable = false
                    dialog.show()
                }else{
                    btn_save_insurance.isClickable = true

                    if (isOk()){
                        dialog.setOnDismissListener {
                            showInfo()
                        }
                        dialog.setSuccess("添加成功")
                        remindViewModel.setCarExtendInfo(data)

                    }else{
                        dialog.setSuccess("添加失败")
                    }
                }


            }

        })

    }


    private fun showInfo(){
        (activity as? RemindActivity)?.run {
            showInfo()
        }
    }

}